import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import Head from 'next/head';
import * as Form from '@radix-ui/react-form';
import TextareaAutosize from 'react-textarea-autosize';
import { test_prompt } from '@/api/ai';


const STORAGE_KEYS = {
  URL: 'test_api_url',
  REQUEST_BODY: 'test_api_request_body',
  RESPONSE: 'test_api_response'
};

@withRouter
class TestApi extends Component {
  state = {
    url: '',
    requestBody: '',
    response: null,
    loading: false,
    error: null,
    iframeKey:'',
  }
  
  componentDidMount() {
    // Load cached values from localStorage
    try {
      const cachedUrl = localStorage.getItem(STORAGE_KEYS.URL);
      const cachedRequestBody = localStorage.getItem(STORAGE_KEYS.REQUEST_BODY);
      const cachedResponse = localStorage.getItem(STORAGE_KEYS.RESPONSE);
      
      this.setState({
        url: cachedUrl || '',
        requestBody: cachedRequestBody || '',
        response: cachedResponse ? JSON.parse(cachedResponse) : null
      });
    } catch (error) {
      console.error('Error loading from localStorage:', error);
    }
  }

  handleUrlChange = (e) => {
    const url = e.target.value;
    this.setState({ url });
    
    // Save to localStorage
    try {
      localStorage.setItem(STORAGE_KEYS.URL, url);
    } catch (error) {
      console.error('Error saving URL to localStorage:', error);
    }
  };

  handleRequestBodyChange = (e) => {
    const requestBody = e.target.value;
    this.setState({ requestBody });
    
    // Save to localStorage
    try {
      localStorage.setItem(STORAGE_KEYS.REQUEST_BODY, requestBody);
    } catch (error) {
      console.error('Error saving request body to localStorage:', error);
    }
  };

  handleSubmit = async () => {
    var selectedModel = window.localStorage.getItem('selectedModel')
    var reqData = {
      "generator_id": selectedModel,
      "prompt": [
          {"role": "user", "content": this.state.url},
          {"role": "system", "content":  this.state.requestBody}
      ]
    }
    var rs = await test_prompt(reqData)
    if (rs.data?.code == 200) {
      var data = rs.data.data
      this.setState({
        response: data
      });
      // Save response to localStorage
      try {
        localStorage.setItem(STORAGE_KEYS.RESPONSE, JSON.stringify(data));
      } catch (error) {
        console.error('Error saving response to localStorage:', error);
      }
      console.log(data)
    }
  };

  render() {
    const { url, requestBody, response, loading, error,iframeKey } = this.state;
    var html = ``

    if(response?.content){
      const arr = response.content.split('转换json失败 -> ');
      if(arr[1])html = arr[1]
    }

    return (
      <>
        <Head>
          <title>API测试</title>
        </Head>
        <div className={styles.pageCont}>
          <div className={styles.title}>API测试工具</div>

        
            <div className={styles.formField}>
              <label className={styles.formLabel} htmlFor="url-input">
                用户提示词
              </label>
              <div className={styles.textareaWrapper}>
                <TextareaAutosize
                  id="url-input"
                  className={styles.textarea}
                  value={url}
                  onChange={this.handleUrlChange}
                  minRows={5}
                  maxRows={10}
                />
              </div>
            </div>

            <div className={styles.formField}>
              <label className={styles.formLabel} htmlFor="request-body">
                系统提示词
              </label>
              <div className={styles.textareaWrapper}>
                <TextareaAutosize
                  id="request-body"
                  className={styles.textarea}
                  value={requestBody}
                  onChange={this.handleRequestBodyChange}
                  minRows={5}
                  maxRows={10}
                />
              </div>
            </div>

            <button
              className={styles.button}
              onClick={this.handleSubmit}
              disabled={loading}
            >
              {loading ? '请求中...' : '发送请求'}
            </button>
        

          {error && (
            <div className={styles.errorContainer}>
              <div className={styles.errorTitle}>错误</div>
              <pre>{error}</pre>
            </div>
          )}

          {response && (
            <div className={styles.resultContainer}>
              <div className={styles.resultTitle}>响应结果</div>
              <pre>{JSON.stringify(response, null, 2)}</pre>
            </div>
          )}
          {
            response && (
              <div className={styles.code}>
                <iframe key={iframeKey} srcdoc={html} />
              </div>
            )
          }
        </div>
      </>
    );
  }
}

export default TestApi;
